{% extends 'base.html' %}
{% load static %}

{% block title %}积分商城 - 城会玩{% endblock %}

{% block style %}
{{ block.super }}
<style>
:root {
    --primary: #FF6B35;
    --primary-dark: #e55a2b;
    --primary-light: rgba(255, 107, 53, 0.1);
    --secondary: #4ECDC4;
    --light: #F8F9FA;
    --dark: #343A40;
    --accent: #E9C46A;
    --gradient-primary: linear-gradient(135deg, #FF6B35 0%, #FF8E53 100%);
    --gradient-secondary: linear-gradient(135deg, #4ECDC4 0%, #44C2B3 100%);
    --gradient-card: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    --shadow: 0 4px 20px rgba(0,0,0,0.08);
    --shadow-hover: 0 8px 30px rgba(0,0,0,0.12);
    --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.points-mall-section {
    background: linear-gradient(135deg, rgba(255, 107, 53, 0.05) 0%, rgba(78, 205, 196, 0.05) 100%);
    min-height: 100vh;
}

/* 积分卡片样式 - 与首页英雄区域风格一致 */
.points-card {
    background: linear-gradient(135deg, rgba(255, 107, 53, 0.9) 0%, rgba(78, 205, 196, 0.8) 100%), url(https://images.unsplash.com/photo-1556742049-0cfed4f6a45d?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80);
    background-size: cover;
    background-position: center;
    color: white;
    border: none;
    border-radius: 20px;
    box-shadow: var(--shadow);
    transition: var(--transition);
    position: relative;
    overflow: hidden;
    margin-bottom: 2rem;
}

.points-card::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
    transform: rotate(30deg);
}

.points-card .card-body {
    position: relative;
    z-index: 2;
    padding: 2rem;
}

.points-display {
    display: flex;
    align-items: baseline;
    gap: 12px;
    margin: 15px 0;
}

.points-number {
    font-size: 3rem;
    font-weight: 700;
    text-shadow: 0 2px 8px rgba(0,0,0,0.15);
    background: linear-gradient(135deg, #fff 0%, #f0f0f0 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.points-label {
    font-size: 1.1rem;
    opacity: 0.9;
    font-weight: 500;
}

/* 统一的商品卡片样式 */
.product-card {
    background: white;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: var(--shadow);
    transition: var(--transition);
    border: none;
    position: relative;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.product-card:hover {
    transform: translateY(-8px);
    box-shadow: var(--shadow-hover);
}

.product-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--gradient-primary);
    z-index: 1;
}

.product-image-container {
    position: relative;
    overflow: hidden;
    height: 220px;
}

.product-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: var(--transition);
}

.product-card:hover .product-image {
    transform: scale(1.05);
}

.product-card-body {
    padding: 1.5rem;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.product-title {
    font-weight: 600;
    margin-bottom: 0.75rem;
    font-size: 1.1rem;
    line-height: 1.4;
    color: var(--dark);
}

.product-description {
    color: #6c757d;
    font-size: 0.9rem;
    line-height: 1.5;
    margin-bottom: 1rem;
    flex: 1;
}

.product-info {
    margin-bottom: 1.5rem;
}

.points-info {
    display: flex;
    align-items: baseline;
    gap: 6px;
    margin-bottom: 0.5rem;
}

.points-value {
    font-size: 1.8rem;
    font-weight: 700;
    color: var(--primary);
    text-shadow: 0 1px 3px rgba(255, 107, 53, 0.3);
}

.points-text {
    color: #666;
    font-size: 1rem;
    font-weight: 500;
}

.points-badge {
    background: var(--gradient-primary);
    color: var(--primary);
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 0.9rem;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(255, 107, 53, 0.3);
    display: inline-block;
}

.original-price {
    text-decoration: line-through;
    color: #999;
    font-size: 0.9rem;
    margin-bottom: 0.5rem;
}

.product-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.85rem;
}

.stock-info {
    color: var(--secondary);
    font-weight: 600;
}

.exchange-count {
    color: #6c757d;
}

.product-actions {
    margin-top: auto;
}

/* 热门商品特殊样式 */
.popular-product-card .product-image-container {
    height: 160px;
}

.popular-product-card .product-card-body {
    padding: 1.25rem;
}

.popular-product-card .product-title {
    font-size: 1rem;
    margin-bottom: 0.5rem;
}

.popular-product-card .points-badge {
    font-size: 0.85rem;
    padding: 5px 12px;
}

.popular-product-card .exchange-count {
    font-size: 0.8rem;
}

/* 标题样式 - 与首页一致 */
.section-title {
    position: relative;
    padding-bottom: 15px;
    margin-bottom: 30px;
    font-weight: 700;
    color: var(--dark);
    font-size: 1.5rem;
}

.section-title::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 60px;
    height: 4px;
    background: var(--gradient-primary);
    border-radius: 2px;
}

/* 按钮样式 - 与首页一致 */
.btn {
    border-radius: 12px;
    padding: 12px 24px;
    font-weight: 600;
    transition: var(--transition);
    border: none;
    position: relative;
    overflow: hidden;
}

.btn-primary {
    background: var(--gradient-primary);
    color: white;
    box-shadow: 0 4px 15px rgba(255, 107, 53, 0.3);
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(255, 107, 53, 0.4);
    background: var(--primary-dark);
    color: white;
}

/* 立即签到、立即兑换、确定按钮的特殊样式 */
#signinBtn,
.exchange-btn,
#confirmExchange,
#successModal .btn-primary {
    background: white !important;
    color: var(--primary) !important;
    border: 2px solid var(--primary) !important;
}

#signinBtn:hover,
.exchange-btn:hover,
#confirmExchange:hover,
#successModal .btn-primary:hover {
    background: var(--primary) !important;
    color: white !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(255, 107, 53, 0.4);
}

.btn-outline-light {
    border: 2px solid rgba(255,255,255,0.3);
    color: white;
    background: rgba(255,255,255,0.1);
    backdrop-filter: blur(10px);
}

.btn-outline-light:hover {
    background: rgba(255,255,255,0.2);
    border-color: rgba(255,255,255,0.5);
    transform: translateY(-2px);
}

.btn-outline-primary {
    border: 2px solid var(--primary);
    color: var(--primary);
    background: transparent;
}

.btn-outline-primary:hover {
    background: var(--primary);
    color: white;
    transform: translateY(-2px);
}

.btn-outline-secondary {
    border: 2px solid #6c757d;
    color: #6c757d;
    background: transparent;
}

.btn-outline-secondary:hover {
    background: #6c757d;
    color: white;
    transform: translateY(-2px);
}

/* 签到卡片 */
.signin-card {
    background: white;
    border-radius: 16px;
    box-shadow: var(--shadow);
    border: none;
    transition: var(--transition);
}

.signin-card:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-hover);
}

.signin-status {
    font-weight: 600;
}

/* 模态框美化 */
.modal-content {
    border: none;
    border-radius: 20px;
    box-shadow: var(--shadow-hover);
    overflow: hidden;
}

.modal-header {
    background: var(--gradient-primary);
    color: white;
    border: none;
    padding: 1.5rem 2rem;
}

.modal-body {
    padding: 2rem;
}

/* 表单控件 */
.form-control, .form-select {
    border: 2px solid #e9ecef;
    border-radius: 12px;
    padding: 12px 16px;
    font-size: 14px;
    transition: var(--transition);
    background: #fafbfc;
}

.form-control:focus, .form-select:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px var(--primary-light);
    background: white;
}

/* 动画效果 */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.product-card {
    animation: fadeInUp 0.6s ease-out forwards;
    opacity: 0;
}

/* 卡片动画延迟 */
.product-card:nth-child(1) { animation-delay: 0.1s; }
.product-card:nth-child(2) { animation-delay: 0.2s; }
.product-card:nth-child(3) { animation-delay: 0.3s; }
.product-card:nth-child(4) { animation-delay: 0.4s; }
.product-card:nth-child(5) { animation-delay: 0.5s; }
.product-card:nth-child(6) { animation-delay: 0.6s; }

/* 筛选器样式 */
.filter-group {
    background: white;
    padding: 12px 16px;
    border-radius: 12px;
    box-shadow: var(--shadow);
}

/* 空状态 */
.empty-state {
    background: white;
    border-radius: 16px;
    padding: 4rem 2rem !important;
    box-shadow: var(--shadow);
    text-align: center;
}

.empty-state i {
    font-size: 4rem;
    opacity: 0.5;
    margin-bottom: 1.5rem;
    color: var(--primary);
}

/* 响应式调整 */
@media (max-width: 768px) {
    .points-number {
        font-size: 2.5rem;
    }

    .points-display {
        gap: 8px;
    }

    .section-title {
        font-size: 1.3rem;
    }

    .btn {
        padding: 10px 20px;
        font-size: 0.9rem;
    }

    .product-image-container {
        height: 180px;
    }

    .popular-product-card .product-image-container {
        height: 140px;
    }

    .filter-group {
        flex-direction: column;
    }

    .points-card .card-body {
        padding: 1.5rem;
    }
}

@media (max-width: 576px) {
    .points-card .text-md-end {
        text-align: left !important;
        margin-top: 1rem;
    }

    .points-card .btn {
        margin-bottom: 0.5rem;
        display: block;
        width: 100%;
    }

    .product-card-body {
        padding: 1rem;
    }

    .popular-product-card .product-card-body {
        padding: 0.875rem;
    }
}

/* 加载动画 */
.loading {
    display: inline-block;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 调试信息 */
.debug-info {
    background: rgba(23, 162, 184, 0.05);
    border: 1px solid rgba(23, 162, 184, 0.1);
    border-radius: 12px;
    color: #0c5460;
}

/* 成功状态 */
.text-success {
    color: var(--secondary) !important;
}

/* 网格布局 */
.popular-products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 1.5rem;
}

.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 1.5rem;
}

/* 与首页一致的卡片内容样式 */
.card-body {
    padding: 1.5rem;
}

.card-title {
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.card-text {
    color: #6c757d;
}

/* 与首页一致的小标签样式 */
.badge {
    font-size: 0.8rem;
    font-weight: 600;
}
</style>
{% endblock %}

{% block content %}
    {% include "nav.html" %}

<div class="points-mall-section py-5">
    <div class="container">
        <div class="row">
            <!-- 用户积分信息 -->
            <div class="col-12 mb-4">
                <div class="card points-card">
                    <div class="card-body py-4">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <h4 class="mb-2 fw-bold">我的积分</h4>
                                <div class="points-display">
                                    <span class="points-number">{{ user_points.available_points }}</span>
                                    <span class="points-label">可用积分</span>
                                </div>
                                <small class="text-white-50 opacity-80">总获得积分: {{ user_points.total_points }}</small>
                            </div>
                            <div class="col-md-6 text-md-end mt-3 mt-md-0">
                                <a href="{% url 'points_history' %}" class="btn btn-outline-light me-2 mb-2">
                                    <i class="fas fa-history me-2"></i>积分历史
                                </a>
                                <a href="{% url 'points_rules' %}" class="btn btn-outline-light me-2 mb-2">
                                    <i class="fas fa-info-circle me-2"></i>积分规则
                                </a>
                                <a href="{% url 'my_exchanges' %}" class="btn btn-outline-light mb-2">
                                    <i class="fas fa-gift me-2"></i>我的兑换
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {% if debug %}
            <div class="col-12 mb-3">
                <div class="card debug-info">
                    <div class="card-body">
                        <h6 class="mb-3">调试信息：</h6>
                        <div class="row">
                            <div class="col-md-3"><strong>用户认证:</strong> {{ user.is_authenticated }}</div>
                            <div class="col-md-3"><strong>今日签到:</strong> {{ today_signed }}</div>
                            <div class="col-md-3"><strong>连续天数:</strong> {{ consecutive_days }}</div>
                            <div class="col-md-3"><strong>签到URL:</strong> {% url 'daily_signin' %}</div>
                        </div>
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- 签到功能 -->
            <div class="col-12 mb-4">
                <div class="card signin-card">
                    <div class="card-body py-4">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h5 class="card-title mb-2 fw-bold">每日签到</h5>
                                <p class="card-text text-muted mb-0">
                                    {% if today_signed %}
                                    <span class="text-success signin-status">
                                        <i class="fas fa-check-circle me-2"></i>今日已签到！连续签到 {{ consecutive_days }} 天
                                    </span>
                                    {% else %}
                                    <i class="fas fa-gift me-2 text-primary"></i>签到可获得积分奖励，连续签到奖励更多！
                                    {% endif %}
                                </p>
                            </div>
                            <div class="col-md-4 text-end">
                                {% if user.is_authenticated %}
                                    {% if not today_signed %}
                                    <button class="btn btn-primary btn-lg px-4" id="signinBtn">
                                        <i class="fas fa-calendar-check me-2"></i>立即签到
                                    </button>
                                    {% else %}
                                    <button class="btn btn-secondary btn-lg px-4" disabled>
                                        <i class="fas fa-check me-2"></i>今日已签到
                                    </button>
                                    {% endif %}
                                {% else %}
                                <a href="{% url 'login' %}" class="btn btn-outline-primary btn-lg px-4">
                                    <i class="fas fa-sign-in-alt me-2"></i>登录后签到
                                </a>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 热门商品 -->
            {% if popular_products %}
            <div class="col-12 mb-5">
                <h4 class="section-title">热门兑换</h4>
                <div class="popular-products-grid">
                    {% for product in popular_products %}
                    <div class="card product-card popular-product-card">
                        <div class="product-image-container">
                            <img src="{{ product.image.url }}" class="product-image" alt="{{ product.name }}">
                        </div>
                        <div class="product-card-body">
                            <h5 class="product-title">{{ product.name }}</h5>
                            <div class="product-info">
                                <div class="points-required mb-2">
                                    <span class="points-badge">{{ product.points_required }} 积分</span>
                                </div>
                            </div>
                            <div class="product-meta">
                                <span class="exchange-count">
                                    <i class="fas fa-exchange-alt me-1"></i>已兑换 {{ product.exchange_count }} 次
                                </span>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
            {% endif %}

            <!-- 所有商品 -->
            <div class="col-12">
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4 gap-3">
                    <h4 class="section-title mb-0">所有商品</h4>
                    <div class="d-flex flex-wrap gap-2 filter-group">
                        <select class="form-select form-select-sm" id="categoryFilter" style="min-width: 120px;">
                            <option value="">全部分类</option>
                            <option value="virtual" {% if selected_category == 'virtual' %}selected{% endif %}>虚拟商品</option>
                            <option value="physical" {% if selected_category == 'physical' %}selected{% endif %}>实物商品</option>
                            <option value="coupon" {% if selected_category == 'coupon' %}selected{% endif %}>优惠券</option>
                        </select>
                        <select class="form-select form-select-sm" id="sortFilter" style="min-width: 140px;">
                            <option value="popular" {% if sort_by == 'popular' %}selected{% endif %}>热门优先</option>
                            <option value="newest" {% if sort_by == 'newest' %}selected{% endif %}>最新上架</option>
                            <option value="points_asc" {% if sort_by == 'points_asc' %}selected{% endif %}>积分从低到高</option>
                            <option value="points_desc" {% if sort_by == 'points_desc' %}selected{% endif %}>积分从高到低</option>
                        </select>
                    </div>
                </div>

                <div class="products-grid">
                    {% for product in products %}
                    <div class="card product-card">
                        <div class="product-image-container">
                            <img src="{{ product.image.url }}" class="product-image" alt="{{ product.name }}">
                        </div>
                        <div class="product-card-body">
                            <h5 class="product-title">{{ product.name }}</h5>
                            <p class="product-description">{{ product.description|truncatewords:15 }}</p>

                            <div class="product-info">
                                <div class="points-info">
                                    <span class="points-value">{{ product.points_required }}</span>
                                    <span class="points-text">积分</span>
                                </div>
                                {% if product.original_price %}
                                <div class="original-price">
                                    原价: ¥{{ product.original_price }}
                                </div>
                                {% endif %}
                                <div class="product-meta">
                                    <span class="stock-info">
                                        <i class="fas fa-box me-1"></i>库存: {{ product.stock }}
                                    </span>
                                    <span class="exchange-count">
                                        <i class="fas fa-exchange-alt me-1"></i>已兑换: {{ product.exchange_count }}
                                    </span>
                                </div>
                            </div>

                            <div class="product-actions">
                                {% if user.is_authenticated %}
                                    {% if product.can_exchange %}
                                        {% if user_points.available_points >= product.points_required %}
                                            <button class="btn btn-primary exchange-btn w-100 py-2"
                                                    data-product-id="{{ product.id }}"
                                                    data-product-name="{{ product.name }}"
                                                    data-points-required="{{ product.points_required }}"
                                                    data-product-category="{{ product.category }}">
                                                <i class="fas fa-shopping-cart me-2"></i>立即兑换
                                            </button>
                                        {% else %}
                                            <button class="btn btn-outline-secondary w-100 py-2" disabled>
                                                <i class="fas fa-lock me-2"></i>积分不足
                                            </button>
                                        {% endif %}
                                    {% else %}
                                        <button class="btn btn-outline-secondary w-100 py-2" disabled>
                                            <i class="fas fa-times me-2"></i>已售罄
                                        </button>
                                    {% endif %}
                                {% else %}
                                    <a href="{% url 'login' %}" class="btn btn-outline-primary w-100 py-2">
                                        <i class="fas fa-sign-in-alt me-2"></i>登录后兑换
                                    </a>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% empty %}
                    <div class="col-12">
                        <div class="empty-state">
                            <i class="fas fa-gift"></i>
                            <h5 class="text-muted mt-3 mb-2">暂无商品</h5>
                            <p class="text-muted">敬请期待更多精彩商品上架</p>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 兑换确认模态框 -->
<div class="modal fade" id="exchangeModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">确认兑换</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="currentProductId">
                <input type="hidden" id="currentProductCategory">

                <div class="text-center mb-4">
                    <i class="fas fa-shopping-cart fa-3x text-primary mb-3"></i>
                    <p class="mb-1">您确定要兑换 <strong id="modalProductName" class="text-primary"></strong> 吗？</p>
                    <p class="mb-0">需要消耗 <strong id="modalPointsRequired" class="text-primary"></strong> 积分。</p>
                </div>

                <!-- 实物商品收货信息 -->
                <div id="shippingInfo" style="display: none;">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">收货地址</label>
                        <textarea class="form-control" id="shippingAddress" rows="3" placeholder="请输入详细的收货地址"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">联系人</label>
                            <input type="text" class="form-control" id="contactName" placeholder="请输入联系人姓名">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">联系电话</label>
                            <input type="tel" class="form-control" id="contactPhone" placeholder="请输入联系电话">
                        </div>
                    </div>
                </div>

                <!-- 虚拟商品提示 -->
                <div id="virtualInfo" style="display: none;">
                    <div class="alert alert-info border-0 bg-light">
                        <i class="fas fa-info-circle text-primary me-2"></i>
                        <span class="fw-medium">此为虚拟商品，兑换成功后系统将自动生成兑换码。</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-outline-secondary px-4" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary px-4" id="confirmExchange">
                    <i class="fas fa-check me-2"></i>确认兑换
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 成功提示模态框 -->
<div class="modal fade" id="successModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center py-4">
                <div id="successMessage"></div>
                <div id="exchangeCode" class="mt-3"></div>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-primary px-4" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    console.log('页面加载完成，开始初始化事件绑定');

    // 获取CSRF token的辅助函数
    function getCsrfToken() {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
        if (csrfToken) {
            return csrfToken.value;
        }

        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, 10) === 'csrftoken=') {
                    cookieValue = decodeURIComponent(cookie.substring(10));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 显示成功消息的函数
    function showSuccessMessage(message, code = null) {
        let successHtml = `
            <i class="fas fa-check-circle text-success fa-4x mb-3"></i>
            <h4 class="text-success fw-bold mb-3">兑换成功！</h4>
            <p class="mb-0">${message}</p>
        `;

        $('#successMessage').html(successHtml);

        if (code) {
            $('#exchangeCode').html(`
                <div class="alert alert-warning border-0 bg-light">
                    <h6 class="fw-bold mb-2">兑换码</h6>
                    <div class="fs-5 fw-bold text-dark mb-2">${code}</div>
                    <small class="text-muted">请妥善保管此兑换码，复制后尽快使用</small>
                </div>
            `).removeClass('d-none');
        } else {
            $('#exchangeCode').addClass('d-none');
        }

        const successModal = new bootstrap.Modal(document.getElementById('successModal'));
        successModal.show();
    }

    // 更新页面状态的函数
    function updatePageAfterSignin(response) {
        const $pointsElement = $('.points-number');
        if ($pointsElement.length) {
            const currentPoints = parseInt($pointsElement.text()) || 0;
            $pointsElement.text(currentPoints + response.points_earned);
        }

        $('#signinBtn')
            .html('<i class="fas fa-check me-2"></i> 今日已签到')
            .removeClass('btn-primary')
            .addClass('btn-secondary')
            .prop('disabled', true);

        $('.card-text.text-muted').html(
            `<span class="text-success signin-status"><i class="fas fa-check-circle me-2"></i>今日已签到！连续签到 ${response.consecutive_days} 天</span>`
        );
    }

    // 签到功能
    $('#signinBtn').click(function() {
        console.log('签到按钮被点击');
        const $btn = $(this);
        const originalText = $btn.html();

        $btn.prop('disabled', true).html('<i class="fas fa-spinner loading me-2"></i> 签到中...');

        const csrfToken = getCsrfToken();

        $.ajax({
            url: '{% url "daily_signin" %}',
            type: 'POST',
            headers: {
                'X-CSRFToken': csrfToken,
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            data: {},
            success: function(response) {
                console.log('签到响应:', response);
                if (response.success) {
                    showSuccessMessage(response.message);
                    updatePageAfterSignin(response);
                } else {
                    alert(response.message);
                    $btn.prop('disabled', false).html(originalText);
                }
            },
            error: function(xhr, status, error) {
                console.error('签到请求失败:', xhr.responseText);
                alert('签到失败，请检查网络连接或稍后重试');
                $btn.prop('disabled', false).html(originalText);
            }
        });
    });

    // 兑换功能
    $(document).on('click', '.exchange-btn', function(e) {
        e.preventDefault();
        console.log('兑换按钮被点击');

        const productId = $(this).data('product-id');
        const productName = $(this).data('product-name');
        const pointsRequired = $(this).data('points-required');
        const productCategory = $(this).data('product-category');

        console.log('兑换商品信息:', { productId, productName, pointsRequired, productCategory });

        $('#currentProductId').val(productId);
        $('#currentProductCategory').val(productCategory);
        $('#modalProductName').text(productName);
        $('#modalPointsRequired').text(pointsRequired);

        if (productCategory === 'physical') {
            $('#shippingInfo').show();
            $('#virtualInfo').hide();
        } else {
            $('#shippingInfo').hide();
            $('#virtualInfo').show();
        }

        $('#shippingAddress').val('');
        $('#contactName').val('');
        $('#contactPhone').val('');

        const exchangeModal = new bootstrap.Modal(document.getElementById('exchangeModal'));
        exchangeModal.show();
    });

    // 确认兑换
    $('#confirmExchange').click(function() {
        const productId = $('#currentProductId').val();
        const productCategory = $('#currentProductCategory').val();
        const $btn = $(this);

        console.log('开始兑换流程:', { productId, productCategory });

        if (!productId) {
            alert('商品ID无效，请刷新页面重试');
            return;
        }

        $btn.prop('disabled', true).html('<i class="fas fa-spinner loading me-2"></i> 兑换中...');

        const formData = {
            shipping_address: '',
            contact_name: '',
            contact_phone: ''
        };

        if (productCategory === 'physical') {
            formData.shipping_address = $('#shippingAddress').val().trim();
            formData.contact_name = $('#contactName').val().trim();
            formData.contact_phone = $('#contactPhone').val().trim();

            if (!formData.shipping_address || !formData.contact_name || !formData.contact_phone) {
                alert('请填写完整的收货信息');
                $btn.prop('disabled', false).html('<i class="fas fa-check me-2"></i>确认兑换');
                return;
            }
        }

        const csrfToken = getCsrfToken();
        const exchangeUrl = `/user/points/exchange/${productId}/`;

        $.ajax({
            url: exchangeUrl,
            type: 'POST',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            headers: {
                'X-CSRFToken': csrfToken
            },
            success: function(response) {
                console.log('兑换响应:', response);
                if (response.success) {
                    let successHtml = `
                        <i class="fas fa-check-circle text-success fa-4x mb-3"></i>
                        <h4 class="text-success fw-bold mb-3">兑换成功！</h4>
                        <p class="mb-0">${response.message}</p>
                    `;

                    if (response.exchange_code) {
                        successHtml = `
                            <i class="fas fa-gift text-primary fa-4x mb-3"></i>
                            <h4 class="text-primary fw-bold mb-3">兑换成功！</h4>
                            <p class="mb-3">${response.message}</p>
                            <div class="alert alert-warning border-0 bg-light">
                                <h6 class="fw-bold mb-2">兑换码</h6>
                                <div class="fs-4 fw-bold text-dark mb-2">${response.exchange_code}</div>
                                <small class="text-muted">请妥善保管此兑换码，复制后尽快使用</small>
                            </div>
                        `;
                    }

                    $('#successMessage').html(successHtml);
                    $('#exchangeCode').addClass('d-none');

                    const $pointsElement = $('.points-number');
                    if ($pointsElement.length && response.new_points !== undefined) {
                        $pointsElement.text(response.new_points);
                    }

                    $('#exchangeModal').modal('hide');
                    const successModal = new bootstrap.Modal(document.getElementById('successModal'));
                    successModal.show();
                } else {
                    alert(response.message);
                }
                $btn.prop('disabled', false).html('<i class="fas fa-check me-2"></i>确认兑换');
            },
            error: function(xhr, status, error) {
                console.error('兑换请求失败:', xhr.responseText);
                alert('兑换失败，请检查网络连接或稍后重试');
                $btn.prop('disabled', false).html('<i class="fas fa-check me-2"></i>确认兑换');
            }
        });
    });

    // 成功模态框关闭后刷新页面
    $('#successModal').on('hidden.bs.modal', function() {
        window.location.reload();
    });

    // 筛选功能
    $('#categoryFilter, #sortFilter').change(function() {
        const category = $('#categoryFilter').val();
        const sort = $('#sortFilter').val();
        const params = new URLSearchParams();

        if (category) params.append('category', category);
        if (sort) params.append('sort', sort);

        window.location.href = '?' + params.toString();
    });

    console.log('所有事件绑定完成');
});
</script>
{% endblock %}